package cn.sgjk.train.business.controller;


import com.google.code.kaptcha.impl.DefaultKaptcha;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/kaptcha")
public class KaptchaController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Qualifier("getDefaultKaptcha")
    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @GetMapping("/image-code/{imageCodeToken}")
    public void imageCode(@PathVariable String imageCodeToken,
                          HttpServletResponse httpServletResponse) throws IOException {
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();

        // 生成验证码字符串
        String createText = defaultKaptcha.createText();

        // key 是通过前端token生成的，为了解决多用户同一个验证码问题
        //将生成的验证码放入redis缓存中，后续验证的时候用到
        redisTemplate.opsForValue().set(imageCodeToken,createText,30, TimeUnit.SECONDS);

        try {
            //使用验证码字符串生成验证码图片
            BufferedImage challenge = defaultKaptcha.createImage(createText);
            ImageIO.write(challenge,"jpg",jpegOutputStream);
        } catch (IOException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        byte[] captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-control","no-store");
        httpServletResponse.setHeader("Pragma","no-cache");
        httpServletResponse.setDateHeader("Expires",0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }
}

